<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-32x32-st.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》,">





  <link rel="alternate" href="/atom.xml" title="卷柏的花期" type="application/atom+xml">






<meta name="description" content="理解对象的分类“宿主对象”与“内置对象”的区别，明白“单体内置对象”的概念，掌握 Global 与 Window 的区别和联系…">
<meta name="keywords" content="读书笔记,《JavaScript 高级程序设计》">
<meta property="og:type" content="article">
<meta property="og:title" content="《JavaScript 高级程序设计》第五章：单体内置对象">
<meta property="og:url" content="http://yoursite.com/2019/05/12/professional-javascript-chapter-5-single-object/index.html">
<meta property="og:site_name" content="卷柏的花期">
<meta property="og:description" content="理解对象的分类“宿主对象”与“内置对象”的区别，明白“单体内置对象”的概念，掌握 Global 与 Window 的区别和联系…">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://yoursite.com/2019/05/12/professional-javascript-chapter-5-single-object/javascript.jpg">
<meta property="og:image" content="http://yoursite.com/2019/05/12/professional-javascript-chapter-5-single-object/window.png">
<meta property="og:updated_time" content="2019-05-11T14:01:01.314Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《JavaScript 高级程序设计》第五章：单体内置对象">
<meta name="twitter:description" content="理解对象的分类“宿主对象”与“内置对象”的区别，明白“单体内置对象”的概念，掌握 Global 与 Window 的区别和联系…">
<meta name="twitter:image" content="http://yoursite.com/2019/05/12/professional-javascript-chapter-5-single-object/javascript.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/05/12/professional-javascript-chapter-5-single-object/">





  <title>《JavaScript 高级程序设计》第五章：单体内置对象 | 卷柏的花期</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband">
    <a href="https://gitee.com/Selaginella/" target="_blank" style="position:absolute;right:0;top:0;border:none"><img src="https://gitee.com/Selaginella/Selaginella/widgets/widget_1.svg" alt="Fork me on Gitee"></a>
    </div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">卷柏的花期</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">随风而动，九死还生</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-source">
          <a href="/source/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-flask"></i> <br>
            
            资源
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/05/12/professional-javascript-chapter-5-single-object/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Selaginella">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="卷柏的花期">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">《JavaScript 高级程序设计》第五章：单体内置对象</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-12T05:51:59+08:00">
                2019-05-11
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <blockquote class="blockquote-center"><img src="/2019/05/12/professional-javascript-chapter-5-single-object/javascript.jpg" alt="&#39;JavaScript 高级程序设计&#39;">理解对象的分类“宿主对象”与“内置对象”的区别，明白“单体内置对象”的概念，掌握 <code>Global</code> 与 <code>Window</code> 的区别和联系…</blockquote>

<a id="more"></a>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><p>在 JS 中对象可以大致分为两类：“内置对象”与“宿主对象”。</p>
<p>“内置对象”指的是由 ECMAScript 实现并提供的与宿主环境无关的对象接口，例如 Object、Function、Array、String、Boolean、Number、Date、RegExp、Error、EvalError、RangeError、ReferenceError、SyntaxError、TypeError、URIError、Global、Math 等都是内置对象。而像 location 、history、Document、XMLHttpRequest 等则都是由宿主环境实现的对象接口。</p>
<p>“单体内置对象” 指的是不具有 <code>prototype</code> 属性的“内置对象”，因此不能结合 <code>new</code> 运算符充当构造函数使用，内部也不存在 <code>[Call]</code> 属性，所以也不能当作函数来调用。<br>ECMAScript 中的“单体内置对象”有：<code>Global</code> 、<code>Math</code> 、<code>JSON</code>，它们的关系如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">─ Global</span><br><span class="line">  ├─JSON</span><br><span class="line">  └─Math</span><br></pre></td></tr></table></figure>
<h2 id="Global"><a href="#Global" class="headerlink" title="Global"></a>Global</h2><p><code>Global</code> 对象是 ECMA-262 中定义的“唯一全局对象”，在任何 ECMAScript 程序执行之前便已存在，它是所有对象或函数最终极的顶层对象，是一切对象的“根”。<br>ECMAScript 中所有的变量、方法以及对象都必须要被保存在一个统一的根对象上，也就是不论存在多少个分支，都必须要有一个唯一的树干一般。也因此 ECMAScript 中并不存在真正的全局变量或函数，所谓全局作用域定义的变量与函数，实际上都是 <code>Global</code> 对象的属性与方法。</p>
<h3 id="值属性"><a href="#值属性" class="headerlink" title="值属性"></a>值属性</h3><p>下面是 ECMA-262 标准中全局对象的值属性。</p>
<table>
<thead>
<tr>
<th style="text-align:left">方法/属性</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">NaN</td>
<td style="text-align:left">表示一个非数值，返回 <code>NaN</code></td>
</tr>
<tr>
<td style="text-align:left">Infinity</td>
<td style="text-align:left">表示一个 +∞ 的值，返回 <code>infinity</code></td>
</tr>
<tr>
<td style="text-align:left">undefined</td>
<td style="text-align:left">表示一个未定义的值，返回 <code>undefined</code></td>
</tr>
</tbody>
</table>
<blockquote>
<p>在数据类型上 <code>NaN</code> 与 <code>infinity</code> 都是数值 <code>number</code> 类型，而 <code>undefined</code> 只是 undefined 类型。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typeof</span> <span class="built_in">window</span>.NaN;          <span class="comment">//"number"</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="built_in">window</span>.infinity;     <span class="comment">//"number"</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="built_in">window</span>.undefined;    <span class="comment">//"undefined"</span></span><br></pre></td></tr></table></figure>
<h3 id="方法属性"><a href="#方法属性" class="headerlink" title="方法属性"></a>方法属性</h3><p>下面是 ECMA-262 标准中全局对象的方法属性。</p>
<table>
<thead>
<tr>
<th style="text-align:left">方法/属性</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">eval</td>
<td style="text-align:left">ECMAScript 解析器(伪)</td>
</tr>
<tr>
<td style="text-align:left">parseInt</td>
<td style="text-align:left">将数值或字符串数值转化为整数(十进制)，支持不同的进制数。</td>
</tr>
<tr>
<td style="text-align:left">parseFloat</td>
<td style="text-align:left">将数值或字符串数值转化为小数(十进制)，支持不同的进制数。</td>
</tr>
<tr>
<td style="text-align:left">isNaN</td>
<td style="text-align:left">是否不是一个数值</td>
</tr>
<tr>
<td style="text-align:left">isFinite</td>
<td style="text-align:left">是否无穷大</td>
</tr>
<tr>
<td style="text-align:left">encodeURI</td>
<td style="text-align:left">URI编码</td>
</tr>
<tr>
<td style="text-align:left">decodeURI</td>
<td style="text-align:left">URI解码</td>
</tr>
<tr>
<td style="text-align:left">encodeURIComponent</td>
<td style="text-align:left">URI编码</td>
</tr>
<tr>
<td style="text-align:left">decodeURIComponent</td>
<td style="text-align:left">URI解码</td>
</tr>
</tbody>
</table>
<h4 id="parseInt-parseFloat"><a href="#parseInt-parseFloat" class="headerlink" title="parseInt / parseFloat"></a>parseInt / parseFloat</h4><p>用于将数值或者是字符串型数值转换为“整数(int)”或者是“浮点数(float)”。<br>这两个方法都支持将“其它进制”的数转换为“十进制”，但是要转换的值必须附加对应进制数的前缀标识 —— <code>0</code>、<code>0x</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">parseInt</span>(<span class="number">070</span>);  <span class="comment">//56</span></span><br><span class="line"><span class="built_in">parseFloat</span>(<span class="number">0x1a</span>); <span class="comment">//26</span></span><br></pre></td></tr></table></figure>
<p><code>parseInt</code> 还支持第二个参数，即指明要转换参数的“基数”，默认为10(十进制)，如果不缺省该参数，则可以缺省被转换参数的前缀标识。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">parseInt</span>(<span class="string">'1a'</span>,<span class="number">16</span>);</span><br></pre></td></tr></table></figure>
<h4 id="encodeURI-encodeURIComponent"><a href="#encodeURI-encodeURIComponent" class="headerlink" title="encodeURI / encodeURIComponent"></a>encodeURI / encodeURIComponent</h4><p><code>encodeURI</code> 与 <code>encodeURIComponent</code> 都是依据 RFC3986 文档规定对 URI 进行编码，在编码时只允许包含英文字母（a-zA-Z）、数字（0-9）、-_.~4个特殊字符以及所有保留字符<code>! * ’ ( ) ; : @ &amp; = + $ , / ? # [ ]</code>。除此之外对于 ASCII 码范围内的，使用 <code>%</code> 加上对应字符十六进制 ASCII 码进行编码，而对于超出 ASCII 码范围外的字符，则采用 UTF-8 编码进行编码。</p>
<p>“保留字符”是 URI 中具有特殊功能和含义的字符，使用“保留字符”可以将 URI 划分成若干个组件，协议、主机、路径等部分。例如 <code>: / ? #</code>，冒号用于分隔协议和主机，斜杠用于分隔主机和路径，问号用于分隔路径和查询参数，井号则用于分隔锚点位置等等。还有一些字符（!$&amp;’()*+,;=）则用于在每个组件内部起到分隔作用，如 = 用于表示查询参数中的键值对，&amp; 符号用于分隔查询多个键值对。当组件中的普通数据包含这些保留字符时，就需要对其进行编码(也就是使用其转义字符进行替换)，不然将会使 URI 发生格式上的错误，也或者会出现数据丢失的情况。例如空格，如果不进行转码 <code>%20</code>，在传输的时候可能会将一些有意义的空格丢失掉。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">encodeURI</span>(<span class="string">'a'</span>); <span class="comment">// "a"</span></span><br><span class="line"><span class="built_in">encodeURIComponent</span>(<span class="string">'a'</span>); <span class="comment">//"a"</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">encodeURI</span>(<span class="string">'|'</span>); <span class="comment">//"%7C"</span></span><br><span class="line"><span class="built_in">encodeURIComponent</span>(<span class="string">'|'</span>);<span class="comment">//"%7C"</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">encodeURI</span>(<span class="built_in">String</span>.fromCharCode(<span class="number">128</span>)); <span class="comment">//"%C2%80"</span></span><br><span class="line"><span class="built_in">encodeURIComponent</span>(<span class="built_in">String</span>.fromCharCode(<span class="number">128</span>)); <span class="comment">//"%C2%80"</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">encodeURI</span>(<span class="string">'我'</span>);    <span class="comment">//"%E6%88%91"</span></span><br><span class="line"><span class="built_in">encodeURIComponent</span>(<span class="string">'我'</span>);   <span class="comment">//"%E6%88%91"</span></span><br></pre></td></tr></table></figure>
<p>总的来说，我们需要对 URL 进行编码，有三点原因：</p>
<p>1.消除歧义: 比如需要将“保留字符”作为普通内容的需求下，也或者需要用可见的编码对一些不可见的字符(控制字符)进行编码从而防止在传输时的错误，也或者是对超出的 ASCII 码表示范围外的字符进行编码，例如中文，以避免乱码可能造成的bug等。<br>2.混淆加密: 对 URL 进行编码在一定程度上也能达到混淆视听的作用。<br>3.安全考量: 有些字符直接放在 URL 中，可能会产生安全隐患，例如 <code>&lt;</code> 与 <code>&gt;</code> 如果不进行编码可能会诱发 XSS 攻击等。</p>
<p>在一般在使用上 <code>encodeURI</code> 用于对整个 URL 进行编码，而 <code>encodeURIComponent</code> 则主要对 URL 中的查询字符串参数或者是 hash 锚点值进行编码。另外就是这两个方法的安全字符范围并不一样<code>。其中</code>encodeURIComponent` 方法的编码范围要更广些。</p>
<p>  encodeURI（82个）：!#$&amp;’()<em>+,/:;=?@-._~0-9a-zA-Z<br>  encodeURIComponent（71个）：!’()</em>-._~0-9a-zA-Z</p>
<blockquote>
<p>最新的 ECMA 标准推荐使用 <code>encodeURI</code> 或者是 <code>encodeURIComponent</code> 来替换 <code>escape</code> 编码方法。</p>
</blockquote>
<h4 id="eval"><a href="#eval" class="headerlink" title="eval()"></a>eval()</h4><ol>
<li>接收一个 JS 代码字符串作为参数，并用这个代码字符串来覆盖当前位置的 <code>eval</code> 代码。</li>
<li>执行这个代码字符串，然后返回执行结果，默认值为 <code>undefined</code>。</li>
<li>可以访问所处执行上下文环境中的作用域链。</li>
<li>非严格模式下 <code>eval</code> 内部定义的标识符（变量、函数）可以被外部执行环境访问。</li>
<li><code>eval</code> 中定义的标识都不会存在“声明提升”，这是因为在执行到 <code>eval</code> 代码之前，它们还是处于字符串的形式。</li>
</ol>
<p>关于 <code>eval()</code> 执行代码字符串并返回结果的示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> sum = <span class="built_in">eval</span>(<span class="string">'1+1'</span>);</span><br><span class="line"><span class="keyword">var</span> data = <span class="built_in">eval</span>(<span class="string">'(&#123;"name":"xiaoming"&#125;)'</span>);</span><br><span class="line"></span><br><span class="line">sum; <span class="comment">//2;</span></span><br><span class="line">data; <span class="comment">//&#123;name: "xiaoming"&#125;</span></span><br></pre></td></tr></table></figure>
<p>关于 <code>eval()</code> 可以访问外部执行环境作用域链以及内部定义的标识符可以被外部代码访问的示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> msg = <span class="string">'hello'</span>;</span><br><span class="line"><span class="built_in">eval</span>(<span class="string">'alert(msg)'</span>);</span><br><span class="line"><span class="built_in">eval</span>(<span class="string">'function say()&#123;alert("world")&#125;'</span>);</span><br><span class="line">say();</span><br></pre></td></tr></table></figure>
<p>这里我们可以理解为当 JS 引擎执行到 eval 代码时，会将 eval 代码所接收的代码字符串转换为真正的 JS 代码，然后插入到原本 eval 代码所在的位置，并替换掉原本的 eval 代码。最终作为当前执行上下文中常规的代码来执行。</p>
<p>关于 <code>eval()</code> 中定义的标识符声明提升问题的示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">say(); <span class="comment">//Uncaught ReferenceError: say is not defined</span></span><br><span class="line"><span class="built_in">eval</span>(<span class="string">'function say()&#123;alert("Hi!")&#125;'</span>);</span><br></pre></td></tr></table></figure>
<p>除了执行 JS 代码字符串，<code>eval</code> 另一个常用场景便是充当 <code>JSON.parse()</code> 的兼容性方法，用来解析 JSON 字符串，但是往往在解析 JSON 时我们还需要用一对 <code>()</code> 圆括号来将 JSON 串括起来。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">eval</span>(<span class="string">'&#123;"age":"26"&#125;'</span>); <span class="comment">//Uncaught SyntaxError: Unexpected token : </span></span><br><span class="line"><span class="built_in">eval</span>(<span class="string">'(&#123;"age":"26"&#125;)'</span>);</span><br></pre></td></tr></table></figure>
<p>原因在于如果没有这对圆括号，<code>{&quot;age&quot;:&quot;26&quot;}</code> 便会被 JS 引擎当作一般的代码进行执行，但是因为存在 <code>{}</code> 花括号运算符，所以又会被识别为一个语句块来执行，然后 <code>&quot;age&quot;</code> 可以被很正常的识别为字符串常量，但是扫描到 <code>:</code> 时，便会抛出语法错误 <code>Unexpected token :</code>。 </p>
<h3 id="构造函数属性"><a href="#构造函数属性" class="headerlink" title="构造函数属性"></a>构造函数属性</h3><p>下面是 ECMA-262 标准中全局对象的构造函数属性。</p>
<table>
<thead>
<tr>
<th style="text-align:left">方法/属性</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">Object</td>
<td style="text-align:left">构造函数 Object，对象引用类型。</td>
</tr>
<tr>
<td style="text-align:left">Function</td>
<td style="text-align:left">构造函数 Function，函数引用类型。</td>
</tr>
<tr>
<td style="text-align:left">Array</td>
<td style="text-align:left">构造函数 Array，数组引用类型。</td>
</tr>
<tr>
<td style="text-align:left">String</td>
<td style="text-align:left">构造函数 String，字符串引用类型。</td>
</tr>
<tr>
<td style="text-align:left">Boolean</td>
<td style="text-align:left">构造函数 Boolean，布尔引用类型。</td>
</tr>
<tr>
<td style="text-align:left">Number</td>
<td style="text-align:left">构造函数 Number，数值引用类型。</td>
</tr>
<tr>
<td style="text-align:left">Date</td>
<td style="text-align:left">构造函数 Date，日期时间引用类型。</td>
</tr>
<tr>
<td style="text-align:left">RegExp</td>
<td style="text-align:left">构造函数 RegExp，正则表达式引用类型。</td>
</tr>
<tr>
<td style="text-align:left">Error</td>
<td style="text-align:left">构造函数 Error</td>
</tr>
<tr>
<td style="text-align:left">EvalError</td>
<td style="text-align:left">构造函数 EvalError</td>
</tr>
<tr>
<td style="text-align:left">RangeError</td>
<td style="text-align:left">构造函数 RangeError</td>
</tr>
<tr>
<td style="text-align:left">ReferenceError</td>
<td style="text-align:left">构造函数 ReferenceError</td>
</tr>
<tr>
<td style="text-align:left">SyntaxError</td>
<td style="text-align:left">构造函数 SyntaxError</td>
</tr>
<tr>
<td style="text-align:left">TypeError</td>
<td style="text-align:left">构造函数 TypeError</td>
</tr>
<tr>
<td style="text-align:left">URIError</td>
<td style="text-align:left">构造函数 URIError</td>
</tr>
</tbody>
</table>
<blockquote>
<p>在ECMAScript 第三版（ECMAScript 3.0）时加入了 <code>try-cacth</code> 异常捕获的支持。</p>
</blockquote>
<h4 id="错误定义"><a href="#错误定义" class="headerlink" title="错误定义"></a>错误定义</h4><ul>
<li><p><strong>Error()</strong><br>基本的错误类型，其他类型都继承自这个类型</p>
</li>
<li><p><strong>EvalError()</strong><br>eval函数没有被正确执行。</p>
</li>
<li><p><strong>RangeError()</strong><br>参数或值超出有效范围。</p>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">new</span> <span class="built_in">Array</span>(<span class="number">-1</span>); <span class="comment">//Uncaught RangeError: Invalid array length</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>ReferenceError()</strong></li>
</ul>
<p>引用错误或引用了一个不存在的变量(标识符)：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">not;<span class="comment">//Uncaught ReferenceError: not is not defined</span></span><br></pre></td></tr></table></figure>
<p>或者将变量赋值给一个无法被赋值的对象：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log()= <span class="number">1</span>; <span class="comment">//Uncaught ReferenceError: Invalid left-hand side in assignment</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>SyntaxError()</strong></li>
</ul>
<p>语法错误。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> <span class="number">1</span>a; <span class="comment">//Uncaught SyntaxError: Invalid or unexpected token</span></span><br><span class="line">&#123; <span class="string">"age"</span>: <span class="number">26</span> &#125; <span class="comment">//Uncaught SyntaxError: Unexpected token :</span></span><br></pre></td></tr></table></figure>
<ul>
<li><strong>TypeError()</strong></li>
</ul>
<p>类型错误。变量或参数不是预期类型。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="keyword">new</span> <span class="number">123</span>; <span class="comment">//Uncaught TypeError: 123 is not a constructor</span></span><br><span class="line"><span class="keyword">var</span> b = &#123;&#125;;</span><br><span class="line"></span><br><span class="line">b.say(); <span class="comment">//Uncaught TypeError: b.say is not a function</span></span><br></pre></td></tr></table></figure>
<p><code>new</code> 运算符的参数应该是一个“构造函数”，而 <code>()</code> 运算符之前应该是个函数类型的标识符。</p>
<ul>
<li><strong>URIError()</strong></li>
</ul>
<p>与 url 相关函数参数不正确，主要是 <code>encodeURI()</code>、<code>decodeURI()</code>、<code>encodeURIComponent()</code>、<code>decodeURIComponent()</code>、<code>escape()</code> 和<code>unescape()</code>这六个函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">decodeURI</span>(<span class="string">'%2'</span>); <span class="comment">//Uncaught URIError: URI malformed</span></span><br></pre></td></tr></table></figure>
<p>这些错误类型，在我们具体编码的时候会根据实际的场景去应用，其中 <code>Error()</code> 是基本错误类型，可以用与扩展自定义的错误。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">DtoB</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> result = <span class="built_in">parseFloat</span>(value);</span><br><span class="line">    <span class="keyword">if</span> (!<span class="built_in">isNaN</span>(result)) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">Number</span>(result).toString(<span class="number">2</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">'请输入一个数值'</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">DtoB(<span class="number">100</span>); <span class="comment">//"1100100"</span></span><br><span class="line">DtoB(<span class="string">'a'</span>); <span class="comment">//Uncaught TypeError: 请输入一个数值</span></span><br></pre></td></tr></table></figure>
<h4 id="错误抛出"><a href="#错误抛出" class="headerlink" title="错误抛出"></a>错误抛出</h4><p>ECMAScript中使用 <code>throw</code> 语句抛出异常/错误类型。</p>
<h4 id="错误捕获"><a href="#错误捕获" class="headerlink" title="错误捕获"></a>错误捕获</h4><p>ECMAScript 中使用 <code>try{}catch(e)finally{}</code> 语句来进行错误的捕获处理。</p>
<h3 id="其它对象属性"><a href="#其它对象属性" class="headerlink" title="其它对象属性"></a>其它对象属性</h3><p>下面是全局对象的其他属性：</p>
<table>
<thead>
<tr>
<th style="text-align:left">方法/属性</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">Math</td>
<td style="text-align:left">数学对象，单体内置对象</td>
</tr>
<tr>
<td style="text-align:left">JSON</td>
<td style="text-align:left">JSON对象，单体内置对象</td>
</tr>
</tbody>
</table>
<h3 id="附加方法属性"><a href="#附加方法属性" class="headerlink" title="附加方法属性"></a>附加方法属性</h3><p>下面是非标准的附加方法属性：</p>
<table>
<thead>
<tr>
<th style="text-align:left">方法/属性</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">escape</td>
<td style="text-align:left">以十六进制的转义序列对字符进行编码</td>
</tr>
<tr>
<td style="text-align:left">unescape</td>
<td style="text-align:left">对使用 <code>escape</code> 方法编码的字符进行解码</td>
</tr>
</tbody>
</table>
<p><code>escape</code> 方法不会对 ASCII 码中的字母、数字 和特定的标点符号 <code>* @ - _ + . /</code>  进行编码，除此之外其他所有的字符都会以十六进制的转义序列进行替换。在格式上，<code>escape</code> 方法返回的字符编码有两种格式，当编码的字符小于 <code>0xFF</code> 范围时,用一个 2位十六进制的转移序列: <code>%xx</code> 表示，大于 <code>0xFF</code> 范围的话则使用 4位 Unicode 编码(UTF-16)<code>%uxxxx</code> 进行表示。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> char =<span class="built_in">String</span>.fromCharCode(<span class="number">0xFF</span>);</span><br><span class="line"><span class="built_in">escape</span>(char); <span class="comment">//"%FF"</span></span><br><span class="line"><span class="built_in">escape</span>(<span class="string">'我'</span>); <span class="comment">//"%u6211"</span></span><br><span class="line"><span class="built_in">escape</span>(<span class="string">'a'</span>); <span class="comment">//”a“</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p><code>escape</code> 与 <code>unescape</code> 都是全局对象附加方法属性，但并非属于标准中的方法，标准更推荐使用 <code>encodeURI</code> 或 <code>encodeURIComponent</code>。</p>
</blockquote>
<h2 id="JSON"><a href="#JSON" class="headerlink" title="JSON"></a>JSON</h2><p><code>JSON</code> 英文全称 JavaScript Object Notation，是一门独立的语言，定义了一种轻量级的数据交换格式。而 <code>Global.JSON</code> 这个单体内置对象则是 ECMAScript 对 <code>JSON</code> 这门语言的实现和支撑。<br><code>Global.JSON</code> 包含两个方法，<code>parse()</code> 和 <code>stringify()</code> 分别用于解析和构造 JSON 数据。<br>JSON 数据中的值可以是 <code>Number、String、Boolean、Null、Object、Array、Date(ISO)</code> 等类型，但不支持 <code>RegExp</code> 以及 <code>Function</code>，如果值必须是一个正则对象或者函数，那么也只能将其转换为字符串形式进行保存。<br>JSON 不会对<code>空格</code>、<code>U+2028</code>、<code>U+2029</code>这三个字符进行转义，详细规范遵循于 <a href="https://www.ietf.org/rfc/rfc4627.txt" target="_blank" rel="noopener">RFC4627</a></p>
<h3 id="parse-text-reviver"><a href="#parse-text-reviver" class="headerlink" title="parse ( text [ , reviver ] )"></a>parse ( text [ , reviver ] )</h3><p><code>parse()</code>  方法用来解析 JSON 字符串，构造由字符串描述的 javaScript 值或对象。</p>
<ul>
<li><code>text</code></li>
</ul>
<p>是一个符合 JSON 格式的字符串，常见的是 <code>Object</code> 与 <code>Array</code> 类型，普通的基本类型数据也可以。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">JSON</span>.parse(<span class="string">'&#123;&#125;'</span>);              <span class="comment">// &#123;&#125;</span></span><br><span class="line"><span class="built_in">JSON</span>.parse(<span class="string">'true'</span>);            <span class="comment">// true</span></span><br><span class="line"><span class="built_in">JSON</span>.parse(<span class="string">'"foo"'</span>);           <span class="comment">// "foo"</span></span><br><span class="line"><span class="built_in">JSON</span>.parse(<span class="string">'[1, 5, "false"]'</span>); <span class="comment">// [1, 5, "false"]</span></span><br><span class="line"><span class="built_in">JSON</span>.parse(<span class="string">'null'</span>);            <span class="comment">// null</span></span><br><span class="line"><span class="built_in">JSON</span>.parse(<span class="string">'1'</span>);               <span class="comment">//  1</span></span><br></pre></td></tr></table></figure>
<ul>
<li><code>reviver(k , v)</code> </li>
</ul>
<p>可选的回调函数，在每次解析的时候都会被调用,可用于按需处理(变换、删除)每次解析的结果。<br>回调函数内必须要通过 <code>return</code> 返回处理的结果，否则 <code>JSON.parse</code> 默认返回的解析结果是 <code>undefined</code>。<br>回调函数接受的两个参数分别是每次解析时的“属性名(k)”和“属性值(v)”，如果 JSON 字符串是数组格式则 <code>k</code> 为每次解析数组元素的索引，如果 JSON 字符串是基本类型则 <code>k</code> 值为空。而 <code>v</code> 值则是每次解析的属性值，如果要删除某个属性，则对应属性的 <code>v</code> 值只需要返回 <code>undefined</code> 即可。<br>回调函数的解析顺序是由内到外的顺序，即存在嵌套的 JSON 结构中，会先按照层级顺序，再按照由内到外的顺序进行遍历解析，当解析到最外层的时候，此时 <code>k</code> 的值便为空了。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="built_in">JSON</span>.parse(<span class="string">'&#123;"t": 5&#125;'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">k, v</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (k === <span class="string">'t'</span>) <span class="keyword">return</span> <span class="literal">undefined</span>; <span class="comment">// 删除属性t</span></span><br><span class="line">    <span class="keyword">return</span> v; </span><br><span class="line">&#125;); </span><br><span class="line"></span><br><span class="line"><span class="built_in">JSON</span>.parse(<span class="string">'&#123;"p": 5&#125;'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">k, v</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (k === <span class="string">''</span>) <span class="keyword">return</span> v; <span class="comment">// 如果到了最顶层，则直接返回属性值，</span></span><br><span class="line">    <span class="keyword">return</span> v * <span class="number">2</span>; <span class="comment">// 否则将属性值变为原来的 2 倍。</span></span><br><span class="line">&#125;); <span class="comment">// &#123; p: 10 &#125;</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">JSON</span>.parse(<span class="string">'&#123;"1": 1, "2": 2,"3": &#123;"4": 4, "5": &#123;"6": 6&#125;&#125;&#125;'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">k, v</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(k); <span class="comment">// 输出当前的属性名，从而得知遍历顺序是从内向外的，</span></span><br><span class="line">    <span class="comment">// 最后一个属性名会是个空字符串。</span></span><br><span class="line">    <span class="keyword">return</span> v; <span class="comment">// 返回原始属性值，相当于没有传递 reviver 参数。</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 1</span></span><br><span class="line"><span class="comment">// 2</span></span><br><span class="line"><span class="comment">// 4</span></span><br><span class="line"><span class="comment">// 6</span></span><br><span class="line"><span class="comment">// 5</span></span><br><span class="line"><span class="comment">// 3 </span></span><br><span class="line"><span class="comment">// "</span></span><br></pre></td></tr></table></figure>
<h3 id="stringify-value-replacer-space"><a href="#stringify-value-replacer-space" class="headerlink" title="stringify ( value [ , replacer [ , space ] ] )"></a>stringify ( value [ , replacer [ , space ] ] )</h3><p><code>stringify()</code> 方法是将一个 javaScript 值(对象或者数组)转换为一个 JSON 字符串，它与 <code>parse</code> 是相反的操作。</p>
<ul>
<li>value</li>
</ul>
<p>需要转换为 JSON 字符串的 javaScript 值，普通的基本类型数据也可以。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">JSON</span>.stringify(&#123;&#125;);                        <span class="comment">// '&#123;&#125;'</span></span><br><span class="line"><span class="built_in">JSON</span>.stringify(<span class="literal">true</span>);                      <span class="comment">// 'true'</span></span><br><span class="line"><span class="built_in">JSON</span>.stringify(<span class="string">"foo"</span>);                     <span class="comment">// '"foo"'</span></span><br><span class="line"><span class="built_in">JSON</span>.stringify([<span class="number">1</span>, <span class="string">"false"</span>, <span class="literal">false</span>]);       <span class="comment">// '[1,"false",false]'</span></span><br><span class="line"><span class="built_in">JSON</span>.stringify(&#123; <span class="attr">x</span>: <span class="number">5</span> &#125;);                  <span class="comment">// '&#123;"x":5&#125;'</span></span><br><span class="line"><span class="built_in">JSON</span>.stringify(<span class="keyword">new</span> <span class="built_in">Date</span>());                  <span class="comment">// ""2019-04-09T06:14:42.730Z""</span></span><br></pre></td></tr></table></figure>
<ul>
<li>replacer</li>
</ul>
<p>可选值，值是一个函数或者数组。<br>如果 <code>replacer</code> 的值是函数，则与 <code>JSON.parse</code> 的 <code>reviver</code> 回调相同，也接收两个参数 <code>replacer(k , v)</code> 分别是每次转换的键值对(key/value)，<code>k</code> 表示属性名，而 <code>v</code> 则是对应的属性值，如果要转换的值是一个数组，则 <code>k</code> 是每次转换的数组元素索引，而若是基本类型的数据，则为空。<br>如果需要删除某个要转换的属性，则只需为对应的属性值返回 <code>undefined</code> 即可。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">replacer</span>(<span class="params">key, value</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="keyword">typeof</span> value === <span class="string">"string"</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">undefined</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> value;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> foo = &#123;<span class="attr">foundation</span>: <span class="string">"Mozilla"</span>, <span class="attr">model</span>: <span class="string">"box"</span>, <span class="attr">week</span>: <span class="number">45</span>, <span class="attr">transport</span>: <span class="string">"car"</span>, <span class="attr">month</span>: <span class="number">7</span>&#125;;</span><br><span class="line"><span class="keyword">var</span> jsonString = <span class="built_in">JSON</span>.stringify(foo, replacer); </span><br><span class="line"><span class="comment">//&#123;"week":45,"month":7&#125;</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>如果转换的值是一个数组类型，则返回的 <code>undefined</code> 会被 <code>null</code> 替代，并不能删除对应的数组元素。</p>
</blockquote>
<p>如果 <code>replacer</code> 的值是数组，则数组元素的值代表将被转换为 JSON 字符串的属性名。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> foo = &#123; <span class="attr">foundation</span>: <span class="string">"Mozilla"</span>, <span class="attr">model</span>: <span class="string">"box"</span>, <span class="attr">week</span>: <span class="number">45</span>, <span class="attr">transport</span>: <span class="string">"car"</span>, <span class="attr">month</span>: <span class="number">7</span> &#125;;</span><br><span class="line"><span class="keyword">var</span> jsonString = <span class="built_in">JSON</span>.stringify(foo, [<span class="string">'foundation'</span>, <span class="string">'model'</span>]);</span><br><span class="line"><span class="comment">//"&#123;"foundation":"Mozilla","model":"box"&#125;"</span></span><br></pre></td></tr></table></figure>
<ul>
<li>space</li>
</ul>
<p>space 参数用来调整 JSON 字符串里面的缩进间距。如果是一个数字, 则在转换为 JSON 字符串时每一级会比上一级多缩进这个数字值的空格（最多10个空格）；如果是一个字符串(“ “、”\t”)，则每一级会比上一级多缩进一个该字符串（或该字符串的前十个字符）。</p>
<p>space 参数的主要作用还是美观 JSON 字符串的展示。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">JSON</span>.stringify(&#123; <span class="attr">uno</span>: <span class="number">1</span>, <span class="attr">dos</span>: <span class="number">2</span>, <span class="attr">values</span>: &#123; <span class="attr">a</span>: <span class="number">1</span>, <span class="attr">b</span>: <span class="number">2</span> &#125; &#125;, <span class="literal">null</span>, <span class="number">4</span>);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">"&#123;</span></span><br><span class="line"><span class="comment">    "uno": 1,</span></span><br><span class="line"><span class="comment">    "dos": 2,</span></span><br><span class="line"><span class="comment">    "values": &#123;</span></span><br><span class="line"><span class="comment">          "a": 1,</span></span><br><span class="line"><span class="comment">          "b": 2</span></span><br><span class="line"><span class="comment">    &#125;</span></span><br><span class="line"><span class="comment">&#125;"</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>
<p>如果一个被转换的对象拥有 <code>toJSON()</code> 方法，那么 <code>stringify</code> 方法会主动调这个 <code>toJSON()</code>，并以该方法的返回结果为最终的转换结果。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">JSON</span>.stringify(&#123; <span class="attr">date</span>: <span class="keyword">new</span> <span class="built_in">Date</span> &#125;); <span class="comment">// new Date().toJOSN() =&gt; new Date().toISOString();</span></span><br></pre></td></tr></table></figure>
<p>利用这个特性，我们可以为要转换的对象自定义一个 <code>toJSON()</code> 方法，从而返回我们需要的转换结果。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">  foo: <span class="string">'foo'</span>,</span><br><span class="line">  toJSON: <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'bar'</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="built_in">JSON</span>.stringify(obj);      <span class="comment">// '"bar"'</span></span><br><span class="line"><span class="built_in">JSON</span>.stringify(&#123;<span class="attr">x</span>: obj&#125;); <span class="comment">// '&#123;"x":"bar"&#125;'</span></span><br></pre></td></tr></table></figure>
<h3 id="Polyfill"><a href="#Polyfill" class="headerlink" title="Polyfill"></a>Polyfill</h3><p>用于在IE7-版本中对 <code>JSON</code> 的兼容性支持。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span> (!<span class="built_in">window</span>.JSON) &#123;</span><br><span class="line">  <span class="built_in">window</span>.JSON = &#123;</span><br><span class="line">    parse: <span class="function"><span class="keyword">function</span>(<span class="params">sJSON</span>) </span>&#123; <span class="keyword">return</span> <span class="built_in">eval</span>(<span class="string">'('</span> + sJSON + <span class="string">')'</span>); &#125;,</span><br><span class="line">    stringify: (<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">var</span> toString = <span class="built_in">Object</span>.prototype.toString;</span><br><span class="line">      <span class="keyword">var</span> isArray = <span class="built_in">Array</span>.isArray || <span class="function"><span class="keyword">function</span> (<span class="params">a</span>) </span>&#123; <span class="keyword">return</span> toString.call(a) === <span class="string">'[object Array]'</span>; &#125;;</span><br><span class="line">      <span class="keyword">var</span> escMap = &#123;<span class="string">'"'</span>: <span class="string">'\\"'</span>, <span class="string">'\\'</span>: <span class="string">'\\\\'</span>, <span class="string">'\b'</span>: <span class="string">'\\b'</span>, <span class="string">'\f'</span>: <span class="string">'\\f'</span>, <span class="string">'\n'</span>: <span class="string">'\\n'</span>, <span class="string">'\r'</span>: <span class="string">'\\r'</span>, <span class="string">'\t'</span>: <span class="string">'\\t'</span>&#125;;</span><br><span class="line">      <span class="keyword">var</span> escFunc = <span class="function"><span class="keyword">function</span> (<span class="params">m</span>) </span>&#123; <span class="keyword">return</span> escMap[m] || <span class="string">'\\u'</span> + (m.charCodeAt(<span class="number">0</span>) + <span class="number">0x10000</span>).toString(<span class="number">16</span>).substr(<span class="number">1</span>); &#125;;</span><br><span class="line">      <span class="keyword">var</span> escRE = <span class="regexp">/[\\"\u0000-\u001F\u2028\u2029]/g</span>;</span><br><span class="line">      <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">stringify</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (value == <span class="literal">null</span>) &#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="string">'null'</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> value === <span class="string">'number'</span>) &#123;</span><br><span class="line">          <span class="keyword">return</span> <span class="built_in">isFinite</span>(value) ? value.toString() : <span class="string">'null'</span>;</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> value === <span class="string">'boolean'</span>) &#123;</span><br><span class="line">          <span class="keyword">return</span> value.toString();</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">typeof</span> value === <span class="string">'object'</span>) &#123;</span><br><span class="line">          <span class="keyword">if</span> (<span class="keyword">typeof</span> value.toJSON === <span class="string">'function'</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> stringify(value.toJSON());</span><br><span class="line">          &#125; <span class="keyword">else</span> <span class="keyword">if</span> (isArray(value)) &#123;</span><br><span class="line">            <span class="keyword">var</span> res = <span class="string">'['</span>;</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; value.length; i++)</span><br><span class="line">              res += (i ? <span class="string">', '</span> : <span class="string">''</span>) + stringify(value[i]);</span><br><span class="line">            <span class="keyword">return</span> res + <span class="string">']'</span>;</span><br><span class="line">          &#125; <span class="keyword">else</span> <span class="keyword">if</span> (toString.call(value) === <span class="string">'[object Object]'</span>) &#123;</span><br><span class="line">            <span class="keyword">var</span> tmp = [];</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">var</span> k <span class="keyword">in</span> value) &#123;</span><br><span class="line">              <span class="keyword">if</span> (value.hasOwnProperty(k))</span><br><span class="line">                tmp.push(stringify(k) + <span class="string">': '</span> + stringify(value[k]));</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">'&#123;'</span> + tmp.join(<span class="string">', '</span>) + <span class="string">'&#125;'</span>;</span><br><span class="line">          &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">'"'</span> + value.toString().replace(escRE, escFunc) + <span class="string">'"'</span>;</span><br><span class="line">      &#125;;</span><br><span class="line">    &#125;)()</span><br><span class="line">  &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="Math"><a href="#Math" class="headerlink" title="Math"></a>Math</h2><p><code>Math</code> 对象是一个“单体内置对象”，具有很多数学常数属性以及代表数学公式的函数方法。<br><code>Math</code> 对象在执行数学计算相关任务时,其性能要比我们使用 JS 代码实现的计算功能更好。但受限于不同的 <code>OS</code> 以及架构的不同，运算结果的精度也会所有不同。</p>
<h3 id="数学常数属性"><a href="#数学常数属性" class="headerlink" title="数学常数属性"></a>数学常数属性</h3><table>
<thead>
<tr>
<th style="text-align:left">属性名</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">E</td>
<td style="text-align:left">自然对数的底数 e 的数字值，约为 2.7182818284590452354</td>
</tr>
<tr>
<td style="text-align:left">LN10</td>
<td style="text-align:left">10 的自然对数的数字值，约为 2.302585092994046。</td>
</tr>
<tr>
<td style="text-align:left">LN2</td>
<td style="text-align:left">2 的自然对数的数字值，约为 0.6931471805599453。</td>
</tr>
<tr>
<td style="text-align:left">LOG2E</td>
<td style="text-align:left">自然对数的底数 e 的以 2 为底数的对数的数字值；约为 1.4426950408889634。</td>
</tr>
<tr>
<td style="text-align:left">LOG10E</td>
<td style="text-align:left">自然对数的底数 e 的以 10 为底数的对数的数字值；约为 0.4342944819032518。</td>
</tr>
<tr>
<td style="text-align:left">PI</td>
<td style="text-align:left">圆的周长与直径之比 π 的数字值，约为 3.1415926535897932。</td>
</tr>
<tr>
<td style="text-align:left">SQRT1_2</td>
<td style="text-align:left">½ 的平方根的数字值，约为 0.7071067811865476。</td>
</tr>
<tr>
<td style="text-align:left">SQRT2</td>
<td style="text-align:left">2 的平方根的数字值，约为 1.4142135623730951。</td>
</tr>
</tbody>
</table>
<h3 id="数学函数属性"><a href="#数学函数属性" class="headerlink" title="数学函数属性"></a>数学函数属性</h3><table>
<thead>
<tr>
<th style="text-align:left">属性名</th>
<th style="text-align:left">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left">abs (x)</td>
<td style="text-align:left">返回 x 的绝对值。</td>
</tr>
<tr>
<td style="text-align:left">ceil (x)</td>
<td style="text-align:left">返回不小于 x 的且为数学整数的最小 ( 接近−∞) 数字值。如果 x 已是整数， 则返回 x。 (若 x 小于 0 但大于 -1, 返回结果是 −0.)</td>
</tr>
<tr>
<td style="text-align:left">floor (x)</td>
<td style="text-align:left">返回不大于 x 的且为数学整数的最大 ( 接近 +∞) 数字值。如果 x 已是整数， 则返回 x。</td>
</tr>
<tr>
<td style="text-align:left">max ( [ value1 [ , value2 [ , … ] ] ] )</td>
<td style="text-align:left">给定零或多个参数，返回其中最大值</td>
</tr>
<tr>
<td style="text-align:left">min ( [ value1 [ , value2 [ , … ] ] ] )</td>
<td style="text-align:left">给定零或多个参数，返回其中最小值</td>
</tr>
<tr>
<td style="text-align:left">random ( )</td>
<td style="text-align:left">返回一个大于或等于 0 但小于 1 的符号为正的数字值，选择随机或在该范围 内近似均匀分布的伪随机，用一个依赖与实现的算法或策略。此函数不需要参数。</td>
</tr>
<tr>
<td style="text-align:left">round (x)</td>
<td style="text-align:left">四舍五入，返回最接近 x 的数学整数</td>
</tr>
<tr>
<td style="text-align:left">pow (x, y)</td>
<td style="text-align:left">返回 x 的 y 次方的依赖于实现的近似值 .</td>
</tr>
<tr>
<td style="text-align:left">exp (x)</td>
<td style="text-align:left">返回 x 的指数的依赖实现的近似值（e 为 x 次方，e 为自然对数的底）。</td>
</tr>
<tr>
<td style="text-align:left">log (x)</td>
<td style="text-align:left">返回 x 的自然对数的依赖于实现的近似值 .</td>
</tr>
<tr>
<td style="text-align:left">sqrt (x)</td>
<td style="text-align:left">返回 x 的平方根的依赖实现的近似值。</td>
</tr>
<tr>
<td style="text-align:left">acos (x)</td>
<td style="text-align:left">返回 x 的反余弦的依赖实现的近似值。结果以弧度形式表示，范围是 +0 到 +π。</td>
</tr>
<tr>
<td style="text-align:left">asin (x)</td>
<td style="text-align:left">返回 x 的反正弦的依赖实现的近似值。结果以弧度形式表示，范围是−π/2 到 +π/2。</td>
</tr>
<tr>
<td style="text-align:left">atan (x)</td>
<td style="text-align:left">返回 x 的反正切的依赖实现的近似值。结果以弧度形式表示，范围是−π/2 到 +π/2。</td>
</tr>
<tr>
<td style="text-align:left">atan2 (y, x)</td>
<td style="text-align:left">返回 – 参数 y 和 x 的商 y/x– 的反正切的依赖实现的近似值，y 和 x 的符 号用于确定返回值的象限。注：命名为 y 的参数为第一个，命名为 x 的参数为第二个，这是有意，是反正切函数俩参数的惯例。结果以弧度形式表示，范围是 −π 到 +π。</td>
</tr>
<tr>
<td style="text-align:left">cos (x)</td>
<td style="text-align:left">返回 x 的余弦的依赖实现的近似值。参数被当做是弧度值。</td>
</tr>
<tr>
<td style="text-align:left">sin (x)</td>
<td style="text-align:left">返回 x 的正弦的依赖实现的近似值。参数被当做是弧度值。</td>
</tr>
<tr>
<td style="text-align:left">tan (x)</td>
<td style="text-align:left">返回 x 的正切的依赖实现的近似值。参数被当做是弧度值。</td>
</tr>
</tbody>
</table>
<p><strong>最大值/最小值方法</strong></p>
<p><code>Math.max()</code> 与 <code>Math.min()</code> 方法结合 <code>apply</code> 方法可以很巧妙的求出数组中的最大值与最小的值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.max.apply(<span class="built_in">Math</span>,[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>]); <span class="comment">//5</span></span><br></pre></td></tr></table></figure>
<blockquote>
<p>其根本原因在于 <code>apply</code> 方法可以接收一个数组作为方法的参数列表。</p>
</blockquote>
<p><strong>舍入方法</strong></p>
<p><code>Math</code> 对象提供的具有舍入功能的方法有：</p>
<ul>
<li><code>Math.ceil(x)</code> ：向上取整，总会返回大于等于 x 的最近整数。</li>
<li><code>Math.floor(x)</code> ：向下取整，总会返回小于等于 x 的最近整数。</li>
<li><code>Math.round(x)</code> ：标准的四舍五入方法。</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.ceil(<span class="number">25.9</span>); <span class="comment">//26</span></span><br><span class="line"><span class="built_in">Math</span>.ceil(<span class="number">25.5</span>); <span class="comment">//26</span></span><br><span class="line"><span class="built_in">Math</span>.ceil(<span class="number">25.1</span>); <span class="comment">//26</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">Math</span>.floor(<span class="number">25.9</span>); <span class="comment">//25</span></span><br><span class="line"><span class="built_in">Math</span>.floor(<span class="number">25.5</span>); <span class="comment">//25</span></span><br><span class="line"><span class="built_in">Math</span>.floor(<span class="number">25.1</span>); <span class="comment">//25</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">Math</span>.round(<span class="number">25.9</span>); <span class="comment">//26</span></span><br><span class="line"><span class="built_in">Math</span>.round(<span class="number">25.5</span>); <span class="comment">//26</span></span><br><span class="line"><span class="built_in">Math</span>.round(<span class="number">25.1</span>); <span class="comment">//25</span></span><br></pre></td></tr></table></figure>
<p>引申开来，也具有舍入特点的其它方法，还有 <code>Number</code> 对象的 <code>toFixed(n)</code> 实例方法。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">25.9</span>.toFixed(); <span class="comment">//26</span></span><br><span class="line"><span class="number">25.5</span>.toFixed(); <span class="comment">//26</span></span><br><span class="line"><span class="number">25.1</span>.toFixed(); <span class="comment">//25</span></span><br></pre></td></tr></table></figure>
<p><strong>随机数方法</strong></p>
<p><code>Math.random()</code> 方法会返回一个大于等于 0 小于不等于 1 的随机数 <code>x&gt;=0 &amp;&amp; x &lt; 1</code>，区间表示: <code>[0,1)</code>。<br>我们可以封装一个函数，来返回指定起始与结束范围内的所有随机数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getRandom</span>(<span class="params">start, end</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> range = end - start + <span class="number">1</span>; <span class="comment">//line1</span></span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Math</span>.floor(<span class="built_in">Math</span>.random() * range + start); <span class="comment">//line2</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>line1</code> : 最后的值 减 起始值 再 加 上起始值 便得到了 [start,end] 之间数的数量。</li>
<li><code>line2</code> : 如果随机数为 0 则加上 start 确保了起始值，如果随机数不为0，Math.floor 则确保了结果不会超出 end。</li>
</ul>
<h2 id="window"><a href="#window" class="headerlink" title="window"></a>window</h2><p><code>Global</code> 对象在不同宿主环境中的实现并不相同，在浏览器中指的是 <code>window</code> 对象，而在 <code>NodeJS</code> 环境中却真的存在一个名叫 <code>global</code> 的顶层对象。这里我们要学习的是浏览器环境下的 <code>window</code> 对象，按照 ECMA-262 标准规定 “全局对象还可以拥有额外的宿主定义的属性。” 所以我们可以将 <code>window</code> 对象看成是 <code>Global</code> 对象的实现超集。</p>
<blockquote>
<p><strong>《JavaScript 高级程序设计》</strong><br>ECMAScript 虽然没有指出如何直接访问 <code>Global</code> 对象，但 Web 浏览器都是将这个全局对象作为 <code>window</code> 对象的一部分加以实现的。</p>
</blockquote>
<p><img src="/2019/05/12/professional-javascript-chapter-5-single-object/window.png" alt="&#39;window&#39;"></p>
<blockquote>
<p>当然在实际浏览器环境中并不存在 <code>window.global</code> 这个对象，但是不妨我们可以将其看作 <code>window.globalThis</code> 对象去理解。 </p>
</blockquote>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wx.jpg" alt="Selaginella 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="Selaginella 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/读书笔记/" rel="tag"># 读书笔记</a>
          
            <a href="/tags/《JavaScript-高级程序设计》/" rel="tag"># 《JavaScript 高级程序设计》</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/05/05/professional-javascript-chapter-5-String/" rel="next" title="《JavaScript 高级程序设计》第五章：String">
                <i class="fa fa-chevron-left"></i> 《JavaScript 高级程序设计》第五章：String
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC80MTkxNC8xODQ2MA"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.jpg" alt="Selaginella">
            
              <p class="site-author-name" itemprop="name">Selaginella</p>
              <p class="site-description motion-element" itemprop="description">知识在于积累，努力必有收获</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/shenguotao2015" target="_blank" title="gitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://gitee.com/Selaginella" target="_blank" title="码云">
                      
                        <i class="fa fa-fw fa-telegram"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://www.cnblogs.com/HCJJ/" target="_blank" title="博客园">
                      
                        <i class="fa fa-fw fa-rss-square"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sgt_ah@163.com" target="_blank" title="Email">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
            </div>
          

          
          

          
          

          
        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#简介"><span class="nav-number">1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Global"><span class="nav-number">2.</span> <span class="nav-text">Global</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#值属性"><span class="nav-number">2.1.</span> <span class="nav-text">值属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#方法属性"><span class="nav-number">2.2.</span> <span class="nav-text">方法属性</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#parseInt-parseFloat"><span class="nav-number">2.2.1.</span> <span class="nav-text">parseInt / parseFloat</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#encodeURI-encodeURIComponent"><span class="nav-number">2.2.2.</span> <span class="nav-text">encodeURI / encodeURIComponent</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#eval"><span class="nav-number">2.2.3.</span> <span class="nav-text">eval()</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#构造函数属性"><span class="nav-number">2.3.</span> <span class="nav-text">构造函数属性</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#错误定义"><span class="nav-number">2.3.1.</span> <span class="nav-text">错误定义</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#错误抛出"><span class="nav-number">2.3.2.</span> <span class="nav-text">错误抛出</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#错误捕获"><span class="nav-number">2.3.3.</span> <span class="nav-text">错误捕获</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#其它对象属性"><span class="nav-number">2.4.</span> <span class="nav-text">其它对象属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#附加方法属性"><span class="nav-number">2.5.</span> <span class="nav-text">附加方法属性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JSON"><span class="nav-number">3.</span> <span class="nav-text">JSON</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#parse-text-reviver"><span class="nav-number">3.1.</span> <span class="nav-text">parse ( text [ , reviver ] )</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#stringify-value-replacer-space"><span class="nav-number">3.2.</span> <span class="nav-text">stringify ( value [ , replacer [ , space ] ] )</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Polyfill"><span class="nav-number">3.3.</span> <span class="nav-text">Polyfill</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Math"><span class="nav-number">4.</span> <span class="nav-text">Math</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#数学常数属性"><span class="nav-number">4.1.</span> <span class="nav-text">数学常数属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数学函数属性"><span class="nav-number">4.2.</span> <span class="nav-text">数学函数属性</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#window"><span class="nav-number">5.</span> <span class="nav-text">window</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-snowflake-o"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Selaginella<span class="with-love"><i class="fa fa-heart"></i></span>Hexo 强力驱动</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>




















  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
